<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 商品编辑 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container" v-loading="loading">
            <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
                <el-tab-pane label="基本信息" name="tab_base">
                    <el-form :model="basicInfo" :rules="baserules" ref="basicInfo" label-width="100px" class="demo-basicInfo">
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="商品名称" prop="title">
                                    <el-input v-model="basicInfo.title"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="商品类别" prop="categoryId">
                                    <el-select
                                        v-model="basicInfo.categoryId"
                                        placeholder="--选择类别--"
                                        clearable
                                        filterable
                                        @change="catChange()"
                                    >
                                        <el-option-group v-for="group in options" :key="group.label" :label="group.label">
                                            <el-option
                                                v-for="item in group.options"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            >
                                            </el-option>
                                        </el-option-group>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="商品状态" prop="status">
                                    <el-radio-group v-model="basicInfo.status.value">
                                        <el-radio label="On">上架</el-radio>
                                        <el-radio label="Off">下架</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>

                            <el-col :span="10">
                                <el-form-item label="库存" prop="stock">
                                    <el-input v-model="basicInfo.stock"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="价格" prop="onLinePrice">
                                    <el-input v-model="basicInfo.onLinePrice" min="0">
                                        <template slot="append">元</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="门市价" prop="marketPrice">
                                    <el-input placeholder="请输入内容" min="0" v-model="basicInfo.marketPrice">
                                        <template slot="append">元</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="佣金" prop="distributionMoney">
                                    <el-input type="number" min="0" v-model="basicInfo.distributionMoney">
                                        <template slot="append">%</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="展示顺序" prop="sort">
                                    <el-input placeholder="请输入内容" min="0" type="number" v-model="basicInfo.sort"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- <el-form-item label="商品推荐" prop="type">
                            <el-checkbox-group v-model="basicInfo.type">
                                <el-checkbox label="美食/餐厅线上商品" name="type"></el-checkbox>
                                <el-checkbox label="地推商品" name="type"></el-checkbox>
                                <el-checkbox label="线下主题商品" name="type"></el-checkbox>
           
                            </el-checkbox-group>
                        </el-form-item> -->

                        <!-- <el-form-item label="商品备注" prop="remark">
                            <el-input type="textarea" v-model="basicInfo.remark"></el-input>
                        </el-form-item> -->
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="图文展示" name="tab_image">
                    <el-form ref="form" label-width="80px">
                        <el-form-item label="图片上传">
                            <el-upload
                                ref="imgUpload"
                                :action="uploadUrl"
                                list-type="picture-card"
                                :limit="5"
                                :file-list="fileList"
                                tip="最多可上传5张图片"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                                :on-success="uploadSuccess"
                            >
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="" />
                            </el-dialog>
                        </el-form-item>
                        <el-form-item label="详细信息">
                            <editor
                                id="editor_id"
                                height="500px"
                                width="100%"
                                :basePath="basePath"
                                :uploadJson="uploadUrl"
                                :items="itemsBars"
                                :content.sync="editorText"
                                :afterChange="afterChange()"
                                :loadStyleMode="false"
                                @on-content-change="onContentChange"
                            ></editor>
                        </el-form-item>
                    </el-form>
                    <!-- <el-button class="editor-btn" type="primary" @click="submit">提交</el-button> -->
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="tab_attr">
                    <el-form ref="attrInfo" label-width="100px" class="demo-basicInfo">
                        <el-row>
                            <el-col :span="6" :key="index" v-for="(attr, index) in attrInfo">
                                <el-form-item :label="attrInfo[index].name" prop="name">
                                    <el-input v-model="attrInfo[index].value"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品规格" name="tab_spec">
                    <el-form label-width="80px">
                        <el-form-item v-for="(item, i) in specList" :label="item.name" :key="item.name">
                            ：
                            <el-checkbox
                                :checked="itemValue.checked"
                                :name="String(i) + '-' + String(j)"
                                :key="itemValue.text"
                                @change="CheckSelect"
                                v-for="(itemValue, j) in specList[i].options"
                                :label="itemValue.text"
                            ></el-checkbox>
                        </el-form-item>
                    </el-form>

                    <el-col :span="24">
                        <el-card shadow="hover">
                            <div slot="header" class="clearfix">
                                <span>规格组合</span>
                            </div>
                            <div v-for="(item, i) in specObjectList" :key="'specObjectList' + String(i)">
                                <el-row style="margin-top: 10px">
                                    <el-col :span="24">
                                        <template v-for="(option, j) in item.specText">
                                            <span>{{ option }}</span>
                                            <el-divider direction="vertical"></el-divider>
                                        </template>
                                        <div class="specinput">
                                            <el-input placeholder="库存数量" type="number" v-model="item.stock" min="0" size="mini">
                                                <template slot="prepend">库存</template>
                                            </el-input>
                                        </div>
                                        <div class="specinput">
                                            <el-input placeholder="输入售价" type="number" v-model="item.price" min="0" size="mini">
                                                <template slot="prepend">价格</template>
                                            </el-input>
                                        </div>

                                        <div class="specinput">
                                            <el-input placeholder="输入门市价" type="number" v-model="item.retailPrice" min="0" size="mini">
                                                <template slot="prepend">门市价</template>
                                            </el-input>
                                        </div>
                                        <div class="specinput">
                                            <el-input placeholder="输入SKU" size="mini" v-model="item.sku">
                                                <template class="tem" slot="prepend">SKU</template>
                                            </el-input>
                                        </div>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-card>
                    </el-col>
                </el-tab-pane>
            </el-tabs>

            <el-row :gutter="20" style="margin: 20px auto; text-align: center">
                <el-button @click="$router.push({ path: '/goods' })">返回</el-button>
                <el-button type="primary" @disabled="disabled" @click="Save('basicInfo')">保存提交</el-button>
            </el-row>
        </div>
    </div>
</template>
<script>
import editor from '@/components/common/kindeditor.vue';
import axios from 'axios';

export default {
    data() {
        return {
            activeName: 'tab_base',
            disabled: true,
            name: 'editor',
            editorText: '', // 双向同步的变量
            basicInfo: {
                id: '',
                name: '',
                status: '1',
                categoryId: '',
                commission: '',

                remark: ''
            },
            goodsImages: [],
            fileList: [],
            loading: true,
            tempSpecList: [],
            specList: [],
            specValueList: [],
            specObjectList: [], //规格组合数据
            specObjectListed: [], //商品id>0时（修改），已经设定的规格组合
            options: [],
            baserules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
                ],
                stock: [{ required: true, message: '请填写商品库存数量', trigger: 'blur' }],
                categoryId: [{ required: true, message: '请选择所属类别', trigger: 'blur' }]
            },
            selectCategory: [],
            dialogImageUrl: '',
            dialogVisible: false,

            attrInfo: [],
            specinfo: [],
            uploadUrl: '',
            basePath: '',
            itemsBars: [
                'justifyleft',
                'justifycenter',
                'justifyright',
                'justifyfull',
                '|',
                'fontname',
                'fontsize',
                'forecolor',
                'hilitecolor',
                'bold',
                'italic',
                'underline',
                '|',
                'image',
                'media',
                'table',
                'hr',
                'emoticons',
                'baidumap',
                'link',
                '|',
                'quickformat',
                'preview',
                'fullscreen'
            ]
        };
    },
    components: {
        editor
    },
    created() {
        // this.uploadUrl = config.uploadUrl + '?tenantName=' + sessionStorage.getItem('tenantName');
        this.loading = true;
        this.getCategorySelect();
        // var id = this.$route.params.id;
        var id = this.$route.query.id;
        if (id > 0) {
            this.getCoodsInfo(parseInt(id));

            //this.getSpecValueObject(parseInt(id));
            this.basicInfo.id = id;
        } else {
            this.basicInfo.id = '';
        }
        this.loading = false;
        this.disabled = false;
        this.basePath = config.fileUrl;
    },
    mounted() {
        setTimeout(() => {
            this.catChange();
        }, 400);
    },
    methods: {
        catChange() {
            var item = this.selectCategory.filter((item) => {
                return item.id == this.basicInfo.categoryId || 0;
            })[0];

            var categoryIds = [0, 0];
            if (item) {
                categoryIds = [item.parentId, item.id];
            }
            this.getGoodsAttr(categoryIds);
        },
        getCategorySelect() {
            var query = {
                title: '',
                parentId: null,
                pageIndex: 1,
                pageSize: 10000 //Number.MAX_SAFE_INTEGER
            };
            axios({
                url: config.gatewayUrl + '/api/product/cat/paged',
                method: 'post',
                data: query
            }).then((res) => {
                if (res.data && res.data.items.length > 0) {
                    this.selectCategory = res.data.items;

                    var firstCategory = res.data.items.filter(function (item) {
                        return item.parentId == 0;
                    });
                    var secondCategory = res.data.items.filter(function (item) {
                        return item.parentId > 0;
                    });

                    var st = [];

                    for (let i = 0; i < firstCategory.length; i++) {
                        var item = {
                            label: firstCategory[i].title,
                            options: []
                        };

                        var filterArray = secondCategory.filter(function (item) {
                            return item.parentId == firstCategory[i].id;
                        });
                        for (let k = 0; k < filterArray.length; k++) {
                            item.options.push({ value: filterArray[k].id, label: filterArray[k].title });
                        }
                        st.push(item);
                    }

                    this.options = st;
                }
            });
        },
        getCoodsInfo(goodsId) {
            var that = this;
            this.loading = true;
            var parmas = {
                id: goodsId
            };
            axios({
                url: config.gatewayUrl + '/api/product/' + goodsId,
                method: 'get'
                //data: parmas
            }).then((res) => {
                this.basicInfo = res.data.proMain;
                this.editorText = res.data.proMain.detail;

                // if (res.data.image != '' && res.data.image != null) {
                //     var imgArray = String(res.data.image).split(',');
                //     if (imgArray.length > 0) {
                //         for (let i = 0; i < imgArray.length; i++) {
                //             if (String(imgArray[i]).indexOf('http') == -1) {
                //                 this.fileList.push({ name: `img${i}`, url: `${config.fileUrl}${imgArray[i]}` });
                //             } else {
                //                 this.fileList.push({ name: `img${i}`, url: `${imgArray[i]}` });
                //             }
                //             this.goodsImages.push(`${imgArray[i]}`);
                //         }
                //     }
                // }
            });
        },
        getSpec: async function () {
            var that = this;
            this.loading = true;
            var categoryId = that.basicInfo.categoryId;
            await axios({
                url: config.gatewayUrl + '/com/ComSpec/GetSpec?categoryId=' + categoryId,
                method: 'get'
            }).then(async (res) => {
                if (res.data == null || res.data.length == 0) {
                    this.loading = false;
                } else {
                    this.tempSpecList = res.data;
                    that.getSpecValue();
                }
            });
        },
        //根据所选类别，获取规格
        getSpecValue: async function () {
            var that = this;
            //config.gatewayUrl="http://localhost:52296";
            var categoryId = that.basicInfo.categoryId;
            await axios({
                url: config.gatewayUrl + '/com/ComSpec/GetSpecValue?categoryId=' + categoryId + '&goodsId=' + that.basicInfo.id,
                method: 'get'
            }).then(async (res) => {
                if (res.data != null && res.data.length > 0) {
                    this.specValueList = res.data;
                    var specList = this.tempSpecList;

                    for (let i = 0; i < specList.length; i++) {
                        var items = res.data.filter((item) => {
                            return item.specId == specList[i].id;
                        });
                        specList[i].options = items;
                    }
                    this.specList = specList;

                    if (that.basicInfo.id > 0 && that.specObjectListed.length > 0) {
                        //已经有保存规格

                        var s = that.setSpec();
                        that.setObject(s);
                    }
                    this.loading = false;
                }
                //this.specValueList = res.data;
            });
        },
        //根据商品Id，获取已经保存的规格
        getSpecValueObject: async function (goodsId) {
            var that = this;
            var categoryId = that.basicInfo.categoryId;
            var query = {
                objectId: that.basicInfo.id
            };
            await axios({
                url: config.gatewayUrl + '/com/comSpec/GetSpecObjectValuePage',
                method: 'post',
                data: query
            }).then(async (res) => {
                if (res.data != null && res.data.list.length > 0) {
                    that.specObjectListed = res.data.list;
                }
                //this.specValueList = res.data;
            });
        },

        //获取自定义属性信息
        getGoodsAttr(categoryIds) {
            var parmas = {
                categoryId: categoryIds,
                id: this.basicInfo.id
            };

            axios({
                url: config.gatewayUrl + '/api/product/attr/paged',
                method: 'post',
                data: parmas
            }).then((res) => {
                this.attrInfo = res.data.items;
            });
        },
        //勾选/取消勾选 规格
        CheckSelect(isChecked, item) {
            var arrayIndexs = item.currentTarget.name.split('-');
            this.specList[parseInt(arrayIndexs[0])].options[parseInt(arrayIndexs[1])].checked = isChecked;

            var specObjectArray = this.setSpec(); //获取到规格组合
            this.setObject(specObjectArray); //将规格再加入价格，门市价，库存等信息
        },
        //将组合后的规格加入 价格，门市价，库存，SKU
        setObject(specObjectArray) {
            var specObjectList = [];
            var that = this;
            //---开始将各组合加入价格，门市价，库存，SKU
            for (let i = 0; i < specObjectArray.length; i++) {
                var valueId = [];
                for (let j = 0; j < specObjectArray[i].length; j++) {
                    var specValue = this.specValueList.filter((item) => {
                        return item.text == specObjectArray[i][j];
                    })[0];
                    valueId.push(specValue.id);
                }
                var item = {};

                item.specText = specObjectArray[i];
                item.valueText = specObjectArray[i].toString();
                item.valueId = valueId.toString();
                item.tenantId = this.basicInfo.tenantId;
                item.objectId = this.basicInfo.id;

                if (that.basicInfo.id > 0 && that.specObjectListed.length > 0) {
                    //编辑商品
                    var tempItem = that.specObjectListed.filter((obj) => {
                        return obj.valueId == item.valueId;
                    })[0];
                    item.retailPrice = tempItem.retailPrice;
                    item.sku = tempItem.sku;
                    item.stock = tempItem.stock;
                    item.price = tempItem.price;
                } else {
                    //新增商品

                    item.retailPrice = 0;
                    item.sku = '';
                    item.stock = 10;
                    item.price = 0;
                }

                specObjectList.push(item);
            }
            this.specObjectList = specObjectList;
        },
        // 组合规格
        setSpec() {
            var specList = this.specList;
            var array = [];

            for (let i = 0; i < specList.length; i++) {
                //循环规格
                // const element = array[index];
                var checkedItemsArray = specList[i].options.filter((item) => {
                    return item.checked;
                });
                if (checkedItemsArray.length > 0) {
                    //array.push(checkedItemsArray);
                    var tempArray = [];
                    for (let j = 0; j < checkedItemsArray.length; j++) {
                        //规格值
                        tempArray.push(checkedItemsArray[j].text);
                    }
                    array.push(tempArray);
                }
            }
            if (array.length < 2) {
                if (typeof array[0] == 'object') {
                    var newArray = [];
                    //如果只勾选/仅仅有一种规格，则每一个规格作为一个数组返回
                    // alert(i);
                    for (var i = 0; i < array[0].length; i++) {
                        var tempStringArray = [];
                        var specValueObject = {};
                        tempStringArray.push(array[0][i]);
                        newArray.push(tempStringArray);
                    }
                    return newArray;
                }
                return array;
            } // return array[0] || []; //返回二维数组本身

            return [].reduce.call(array, function (col, set) {
                var res = [];
                col.forEach(function (c) {
                    set.forEach(function (s) {
                        var t = [].concat(Array.isArray(c) ? c : [c]);
                        t.push(s);
                        res.push(t);
                    });
                });

                return res;
            });
        },
        // 保存提交
        Save(formName) {
            var that = this;

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var dto = that.basicInfo;
                    dto.detail = this.editorText;
                    dto.price = parseFloat(dto.price);
                    dto.retailPrice = parseFloat(dto.retailPrice);
                    dto.commission = parseFloat(dto.commission);
                    dto.stock = parseInt(dto.stock);
                    dto.sort = parseInt(dto.sort);
                    dto.image = String(that.goodsImages);

                    axios
                        .post(config.gatewayUrl + '/product/goods/post', dto)
                        .then((res) => {
                            if (typeof res.data === 'number' && !isNaN(res.data)) {
                                if (that.basicInfo.id == 0) {
                                    that.basicInfo.id = res.data;
                                }
                                that.SaveAttr();
                                that.SaveSpec();
                                that.$message.success(`保存成功!`);
                                //that.$router.push({ path: '/goods' });
                            } else {
                                that.$message.error(res.data.promptMsg);
                                console.log(res);
                            }
                        })
                        .catch((error) => {
                            console.log(error); //  错误处理 相当于error
                        });

                    that.$refs.form.clearValidate();
                } else {
                    return false;
                }
            });
        },
        //保存属性
        SaveAttr() {
            var that = this;
            var attrs = this.attrInfo;
            for (let i = 0; i < attrs.length; i++) {
                this.attrInfo[i].objectId = this.basicInfo.id;
            }
            axios
                .post(config.gatewayUrl + '/com/commonattrvalue/post', this.attrInfo)
                .then((res) => {
                    if (typeof res.data === 'number' && !isNaN(res.data)) {
                    } else {
                        that.$message.error(res.data.promptMsg);
                        console.log(res);
                    }
                })
                .catch((error) => {
                    console.log(error); //  错误处理 相当于error
                });
        },
        //保存规格
        SaveSpec() {
            var specs = this.specObjectList;
            for (let i = 0; i < specs.length; i++) {
                // const element = array[i];
                specs[i].stock = parseInt(specs[i].stock);
                specs[i].price = parseFloat(specs[i].price);
                specs[i].retailPrice = parseFloat(specs[i].retailPrice);
            }
            axios
                .post(config.gatewayUrl + '/com/ComSpec/PostObject', specs)
                .then((res) => {
                    if (typeof res.data === 'number' && !isNaN(res.data)) {
                    } else {
                        that.$message.error(res.data.promptMsg);
                        console.log(res);
                    }
                })
                .catch((error) => {
                    console.log(error); //  错误处理 相当于error
                });
        },
        //Tab切换
        handleClick(tab, event) {
            if (this.basicInfo.categoryId == '') {
                return;
            }
            var tab = this.activeName;
            var item = this.selectCategory.filter((item) => {
                return item.id == this.basicInfo.categoryId;
            })[0];

            var categoryIds = [item.parentId, item.id];
            // this.getGoodsAttr(categoryIds);
            if (tab == 'tab_attr') {
            }
            if (tab == 'tab_spec') {
                //this.$message('正在研发中...');
                this.tempSpecList = [];
                this.specList = [];
                this.specValueList = [];
                this.loading = true;
                //this.getSpec();
                //this.setSpec();
            }
            console.log(tab, event);
        },
        handleRemove(file, fileList) {
            var url = file.url;
            if (url == undefined) {
                url = file.response.url;
            }
            url = String(url).replace(config.fileUrl, '');
            var index = this.goodsImages.indexOf(url);
            this.goodsImages.splice(index, 1);
        },
        uploadSuccess(data) {
            if (this.goodsImages.length < 5) {
                this.goodsImages.push(data.url);
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        onContentChange(val) {
            this.editorTextCopy = val;
            // window.console.log(this.editorTextCopy);
        },
        afterChange(val) {
            console.log(val);
        }
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        }
    }
};
</script>

<style>
.specinput {
    display: inline-block;
}
.specinput .el-input-group > .el-input-group__prepend {
    padding: 0 5px !important;
    border-radius: 0;
}
.specinput .el-input__inner,
.specinput .el-input-group__append {
    border-radius: 0;
}
.specinput .el-input__inner {
    padding: 0 10px;
    width: 100px;
}
</style>